//
//  ProfileViewController.m
//  zhijian
//
//  Created by lcb on 2019/2/24.
//  Copyright © 2019 lcb. All rights reserved.
//

#import "ProfileViewController.h"
#import "AppDelegate.h"
#import "ProfileEditViewController.h"
#import "ZLPhotoActionSheet.h"
#import "ZLPhotoManager.h"
#import "ZLCustomCamera.h"
@interface ProfileViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong) NSArray *dataSource;

@end

@implementation ProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self hyb_navWithLeftImage:@"back" title:@"个人信息" leftClicked:^(UIButton *sender) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self initData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
- (void)initData{
    
    _dataSource = [NSArray arrayWithObjects:@"头像",@"姓名",@"企业",@"职称",@"修改密码", nil];
    [self.tableView reloadData];
    
}

-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    return _tableView;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 80;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"TEXTCELL"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
   
    NSString *title = [_dataSource objectAtIndex:indexPath.row];
    cell.textLabel.text =title;
    switch (indexPath.row) {
        case 0:
        {
            UIImageView *iconImg = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-90, 10, 60, 60)];
            //设置边框圆角的弧度
            [iconImg.layer setMasksToBounds:YES];
            [iconImg.layer setCornerRadius:30 / 2.0];
            iconImg.userInteractionEnabled = YES;
            if ([[BaseShare sharedBaseShare] getUser].headImg.length==0) {
                iconImg.image =[UIImage imageNamed:@"avater"];
            }else{
                [iconImg imageWithUrlStr:[[BaseShare sharedBaseShare] getUser].headImg placeholder:[UIImage imageNamed:@"avater"]];
            }
            UITapGestureRecognizer *singleTap =   [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction:)];
            [iconImg addGestureRecognizer:singleTap];
            [cell addSubview:iconImg];
        }
            break;
        case 1:{
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            NSString *versionString = [[BaseShare sharedBaseShare] getUser].userName;
            CGSize versionSize = [versionString sizeWithFont:[UIFont systemFontOfSize:16.0f]];
            UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-versionSize.width-40, 15, versionSize.width, versionSize.height)];
            versionLabel.backgroundColor = [UIColor clearColor];
            versionLabel.font = [UIFont systemFontOfSize:16.0f];
            versionLabel.textColor = UIColorOfHex(0x757575);
            versionLabel.textAlignment = NSTextAlignmentRight;
            versionLabel.text =versionString;
            versionLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
            [cell addSubview:versionLabel];
        }break;
        case 2:{
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            NSString *versionString =  [[BaseShare sharedBaseShare] getUser].companyName;
            CGSize versionSize = [versionString sizeWithFont:[UIFont systemFontOfSize:16.0f]];
            UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-versionSize.width-40, 15, versionSize.width, versionSize.height)];
            versionLabel.backgroundColor = [UIColor clearColor];
            versionLabel.font = [UIFont systemFontOfSize:16.0f];
            versionLabel.textColor = UIColorOfHex(0x757575);
            versionLabel.textAlignment = NSTextAlignmentRight;
            versionLabel.text = versionString;
            versionLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
            [cell addSubview:versionLabel];
        }break;
        case 3:{
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            NSString *versionString = [[BaseShare sharedBaseShare] getUser].userTitle;
            CGSize versionSize = [versionString sizeWithFont:[UIFont systemFontOfSize:16.0f]];
            UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-versionSize.width-40, 15, versionSize.width, versionSize.height)];
            versionLabel.backgroundColor = [UIColor clearColor];
            versionLabel.font = [UIFont systemFontOfSize:16.0f];
            versionLabel.textColor = UIColorOfHex(0x757575);
            versionLabel.textAlignment = NSTextAlignmentRight;
            versionLabel.text = versionString;
            versionLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
            [cell addSubview:versionLabel];
        }break;
        case 4:{
           cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }break;
        default:
            break;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 1:
        {
            ProfileEditViewController *pedit =[[ProfileEditViewController alloc] init];
            pedit.navTitle =@"修改姓名";
            pedit.profileType =@"name";
            [self.navigationController pushViewController:pedit animated:YES];
        }
            break;
        case 2:
        {
//            ProfileEditViewController *pedit =[[ProfileEditViewController alloc] init];
//            pedit.navTitle =@"修改企业";
//            pedit.profileType =@"company";
//            [self.navigationController pushViewController:pedit animated:YES];
        }
            break;
        case 3:
        {
//            ProfileEditViewController *pedit =[[ProfileEditViewController alloc] init];
//            pedit.navTitle =@"修改职业";
//            pedit.profileType =@"profession";
//            [self.navigationController pushViewController:pedit animated:YES];
        }
            break;
        case 4:
        {
            ProfileEditViewController *pedit =[[ProfileEditViewController alloc] init];
            pedit.navTitle =@"修改密码";
            pedit.profileType =@"password";
            [self.navigationController pushViewController:pedit animated:YES];
            
        }
            break;
        default:
            break;
    }
    
}
- (ZLPhotoActionSheet *)photoActionSheet
{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    actionSheet.configuration.languageType = ZLLanguageChineseSimplified;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    actionSheet.configuration.allowSelectGif = NO;
    actionSheet.configuration.allowSelectVideo = NO;
    actionSheet.configuration.allowSelectLivePhoto = NO;
    //如果调用的方法没有传sender，则该属性必须提前赋值
    actionSheet.sender = self;
    WEAKSELF
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        if (images.count>0) {
            [weakSelf uploadFile:images callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
                [BaseToast show:response.message];
                [[Api sharedApi] updateUserInfo:response.data userName:[[BaseShare sharedBaseShare] getUser].userName callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
                     [BaseToast show:response.message];
                    [[BaseShare sharedBaseShare] getUserInfo];
                }];
            }];
          
        }
        
    }];
    actionSheet.cancleBlock = ^{
        NSLog(@"取消选择图片");
    };
    
    return actionSheet;
}
//点击事件
-(void)singleTapAction:(UIGestureRecognizer *)gest
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle: @"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self takePhoto];
    }];
    [alertVc addAction:takePhotoAction];
    UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[self photoActionSheet] showPhotoLibrary];
    }];
    [alertVc addAction:imagePickerAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:cancelAction];

    [self presentViewController:alertVc animated:YES completion:nil];
}
-(void)uploadFile:(NSArray*)images callback:(callbackBlock)callback
{
    [[Api sharedApi] uploadImages:images callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
        [BaseToast show:response.message];
        if (callback) {
            callback(response,errorMsg);
        }
    }];
}
-(void)takePhoto
{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
       [BaseToast show:message];
        return;
    }
    if (![ZLPhotoManager haveMicrophoneAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoMicrophoneAuthorityText), kAPPName];
        [BaseToast show:message];
        return;
    }
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    zl_weakify(self);
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        if (image) {
            [weakSelf uploadFile:@[image] callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
                [BaseToast show:response.message];
                [[Api sharedApi] updateUserInfo:response.data userName:[[BaseShare sharedBaseShare] getUser].userName callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
                    [BaseToast show:response.message];
                    [[BaseShare sharedBaseShare] getUserInfo];
                }];
            }];
            
        }
    };
    [self presentViewController:camera animated:YES completion:nil];
}
@end
